package com.skyworthclub.competition.utils.service;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @author li
 * @version 1.0
 * @since 18-10-16 下午12:15
 * 发送邮件工具类（待重构）
 **/
@Component
public class EmailService {

    private final UserService userService;

    private final JavaMailSender javaMailSender;

    private Logger logger = LoggerFactory.getLogger(EmailService.class);

    /**
     *  站点邮件地址
     */
    private static final String SITE_EMAIL = "zulongli@aliyun.com";

    /**
     * 管理员邮件地址
     */
    private static final String ADMIN_EMAIL = "zulongli@aliyun.com";

    /**
     * subject
     */
    private static final String SUBJECT = "百舸争流";

    @Autowired
    public EmailService(JavaMailSender javaMailSender, UserService userService) {
        this.javaMailSender = javaMailSender;
        this.userService = userService;
    }

    public void sendValidationCodeMail(String emailTo, String codeFor, String emailKey, HttpSession httpSession) {
        //生成验证码
        String code = generateCode();
        //构建邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(SUBJECT);
        mailMessage.setText("您的邮箱验证码为：" + code);
        mailMessage.setFrom(SITE_EMAIL);
        mailMessage.setTo(emailTo);
        //发送邮件
        javaMailSender.send(mailMessage);
        //保存邮箱和验证码在会话中，以供后面验证
        httpSession.setAttribute(codeFor, code);
        httpSession.setAttribute(emailKey, emailTo);
        //设置有效期为10分钟
        httpSession.setMaxInactiveInterval(10 * 60);
    }

    /** 验证码生成器
     * @return 验证码
     */
    private static String generateCode() {
        Random random = new Random();
        double aDouble = random.nextDouble();
        int code = (int) (aDouble * 1000000);
        int lowest = 100000;
        if (code < lowest) {
            return "0" + code;
        } else {
            return code + "";
        }
    }

    @Async
    public void feedbackNotice(String feedbackContent) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(SUBJECT);
        message.setText("您收到一份反馈：\n" + feedbackContent);
        message.setFrom(SITE_EMAIL);
        message.setTo(ADMIN_EMAIL);
        //发送邮件
        javaMailSender.send(message);
    }

    /** 比赛信息审核通过邮件提醒
     * @param publisher 比赛发布者
     * @param matchName 比赛名称
     */
    @Async
    public void matchPublishPassNotice(String publisher, String matchName) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id", "email");
        wrapper.eq("username", publisher);
        User user = userService.selectOne(wrapper);
        if (user == null) {
            logger.error("用户不存在！");
            return;
        }
        //构建电子邮件并发送
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(user.getEmail());
        mailMessage.setFrom(SITE_EMAIL);
        mailMessage.setSubject(SUBJECT);
        mailMessage.setText("您发布的名为:\n" + matchName + "\n的比赛信息已通过审核！");
        javaMailSender.send(mailMessage);

    }

    /** 比赛信息未审核通过邮件提醒
     * @param publisher 比赛发布者
     */
    @Async
    public void matchPublishUnPassNotice(String publisher,String matchName, String cause) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id", "email");
        wrapper.eq("username", publisher);
        User user = userService.selectOne(wrapper);
        if (user == null) {
            logger.error("用户不存在！");
            return;
        }

        //构建电子邮件并发送
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(user.getEmail());
        mailMessage.setFrom(SITE_EMAIL);
        mailMessage.setSubject(SUBJECT);
        mailMessage.setText("很遗憾，您发布的名为\n"+matchName+"\n的比赛信息未能通过审核！原因如下：\n" + cause);
        javaMailSender.send(mailMessage);
    }

    /** 通知管理员审核信息
     * @param matchName 比赛名称
     * @param type  类型=更新/新增
     */
    @Async
    public void checkingNotice(String matchName, int type) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(SUBJECT);
        if (type == 1) {
            //新上传比赛信息
            message.setText("有新上传的名为：\n  " + matchName + "\n的比赛信息，请审核！");
        } else if (type == 0) {
            //更新比赛信息
            message.setText("ID为：\n  " + matchName + "\n的比赛信息有更新，请审核！");
        }
        message.setFrom(SITE_EMAIL);
        message.setTo(ADMIN_EMAIL);
        //发送邮件
        javaMailSender.send(message);
    }
}
